<template>
  <a-card :bordered="false" class="card-area">
    <div class="table-page-search-wrapper">
      <a-form layout="vertical">
        <a-row :gutter="48">
          <a-col :md="8" :sm="12">
            <a-form-item label="学科类别">
              <a-select v-model="queryParam.xklb" :allowClear="true">
                <a-select-option v-for="i in selectMenu.xklb" :key="i.id" :value="i.code">{{ i.name }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="12">
            <a-form-item label="学科代码">
              <a-input v-model="queryParam.xkdm" placeholder=""/>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="12">
            <a-form-item label="学科名称">
              <a-input v-model="queryParam.xkmc" placeholder=""/>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="12">
            <span class="table-page-search-submitButtons" >
              <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
              <a-button type="primary" @click="openAdd">添加</a-button>
              <a-button type="primary" @click="exportEcl">导出</a-button>
              <a-button type="primary" @click="batchDelete">删除</a-button>
              <a-button style="margin-left: 8px" @click="() => queryParam = {}">重置</a-button>
              <!-- <a @click="advanced = !advanced" style="margin-left: 8px">
                {{ advanced ? '收起' : '展开' }}
                <a-icon :type="advanced ? 'up' : 'down'"/>
              </a> -->
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <subject-edit
      ref="subjectEdit"
      :visible.sync="visible"
      :editId.sync="editId"
      :selectMenu.sync="selectMenu"
      :confirmLoading.sync="confirmLoading"
      @cancel="visible = false"
      @create="handleCreate"
    />
    <s-table
      ref="table"
      size="default"
      rowKey="key"
      :columns="columns"
      :data="loadData"
      :alert="options.alert"
      :rowSelection="options.rowSelection">

      <span slot="serial" slot-scope="text, record, index">
        {{ index + 1 }}
      </span>

      <a slot="operation" slot-scope="a,b" @click="openEdit(b)">修改</a>
    </s-table>

  </a-card>
</template>

<script>
import { STable } from '~'
import subjectEdit from './subjectEdit'
import moment from 'moment'

export default {
  components: {
    STable,
    subjectEdit
  },
  data () {
    return {
      // 高级搜索 展开/关闭
      advanced: true,
      visible: false,
      editId: null,
      // 查询参数
      queryParam: {},
      postParams: {
        sssfbz: true
      },
      // 表头
      columns: [
        {
          title: '序号',
          scopedSlots: { customRender: 'serial' }
        },
        {
          title: '学科代码',
          dataIndex: 'xkdm'
        },
        {
          title: '学科名称',
          dataIndex: 'xkmc'
        },
        {
          title: '学科类别',
          dataIndex: 'xklbmc'
        },
        {
          title: '父级学科',
          dataIndex: 'fjxkmc'
        },
        {
          title: '操作',
          dataIndex: 'operation',
          scopedSlots: { customRender: 'operation' }
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        console.log('loadData.parameter', parameter)
        parameter.pageNum = parameter.pageNo
        let params = Object.assign(this.queryParam, parameter)
        return this.$api.base.subjectList(params).then(res => {
          return {
            data: res.data.rows,
            pageNo: parameter.pageNo,
            pageSize: parameter.pageSize,
            totalPage: Math.ceil(res.data.total / parameter.pageSize),
            totalCount: res.data.total
          }
        })
      },
      selectedRowKeys: [],
      selectedRows: [],

      // custom table alert & rowSelection
      options: {
        alert: { show: true, clear: () => { this.selectedRowKeys = [] } },
        rowSelection: {
          selectedRowKeys: this.selectedRowKeys,
          onChange: this.onSelectChange
        }
      },
      optionAlertShow: true, // 是否显示alert，已选中
      confirmLoading: false,
      selectMenu: {}
    }
  },
  created () {
    this.initSelectMenu()
  },
  methods: {
    filterOption (value, op) {
      return op.componentOptions.children[0].text.indexOf(value) !== -1
    },
    initSelectMenu () {
      let allRequest = [
        this.$api.base.dictionaryData('TYPE0345'),
        this.$api.base.subjectAll(),
        this.$api.base.dictionaryData('TYPE0068'),
        this.$api.base.collegeAll()
      ]
      Promise.all(allRequest).then(res => {
        this.selectMenu = {
          xklb: res[0].data, // 学科类别
          subject: res[1].data, // 学科
          xksqm: res[2].data, // 学科授权码
          yx: res[3].data
        }
      })
    },
    handleCreate () {
      const form = this.$refs.subjectEdit.form
      form.validateFields(async (err, values) => {
        if (err) {
          return
        }
        // 循环 日期参数，格式化
        this.$DateToString(values)
        this.confirmLoading = true
        let baseApi = this.editId ? 'subjectUpdate' : 'subjectAdd'
        let res = await this.$api.base[baseApi](Object.assign({id: this.editId}, values, {fjxkdm: values.fjxkdm || ''}))
        this.$message.success(res.msg)
        this.$refs.table.refresh(false)
        this.confirmLoading = false
        form.resetFields()
        this.visible = false
        this.getSubjectAll()
      })
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    batchDelete () {
      if (!this.selectedRowKeys.length) {
        this.$message.warning('请选择需要删除的学科信息')
        return
      }
      this.$confirm({
        title: '确定删除所选中的学科信息?',
        content: '当您点击确定按钮后，这些记录将会被彻底删除',
        centered: true,
        onOk: () => {
          let subjectIds = []
          this.selectedRows.forEach(subject => {
            subjectIds.push(subject.id)
          })
          this.$api.base.subjectDelete(subjectIds.join(',')).then(() => {
            this.$message.success('删除成功')
            this.selectedRowKeys = []
            this.selectedRows = []
            this.$refs.table.refresh(false)
            this.$refs.table.clearSelected()
            this.getSubjectAll()
          })
        },
        onCancel: () => {
        }
      })
    },
    getSubjectAll() {
      this.$api.base.subjectAll().then(res => {
        this.$set(this.selectMenu, 'subject', res.data)
      })
    },
    openAdd () {
      this.editId = null
      this.visible = true
      this.$refs.subjectEdit.form.resetFields()
    },
    openEdit (subject) {
      this.visible = true
      this.$nextTick(() => {
        for (const key in subject) {
          if (['bssqny', 'sssqny', 'sbzdxkpzny', 'gjzdxkpzny', 'xksqny'].includes(key)) {
            subject[key] = moment(subject[key])
          }
        }
        this.$refs.subjectEdit.form.resetFields()
        this.$refs.subjectEdit.form.setFieldsValue(subject)
        this.editId = subject.id
      })
    },
    exportEcl(){
      let params = {...this.queryParam}
      delete params.pageNum
      delete params.pageSize
      this.$export('base/xkxx/exportList', params)
    }
  }
}
</script>
